<?php
/**
 * @author AlexEllo https://github.com/AlexEllo
 * @copyright (c) 2014 AlexEllo
 * MongoDB pagination adapter for phalcon
 */
namespace Core\Paginator\Adapter;

use Phalcon\Paginator\Adapter as BaseAdapter;
use Phalcon\Paginator\Exception;
use Phalcon\Mvc\CollectionInterface;

/**
 * Class Collection
 * @package Core\Paginator\Adapter
 */
class Collection extends BaseAdapter
{

    /**
     * Cursor.
     *
     * @var \MongoCursor;
     */
    protected $_data;

    protected $_query;

    protected $_collection;

    protected $_skip = 5;

    /**
     * Adapter constructor.
     *
     * @param array $config Config.
     */
    public function __construct($config)
    {

        if (isset($config['data'])) {
            $this->_data = $config['data'];
        }
        $this->_query = $config['query'];
        if (!isset($config['query']['limit'])) {
            throw new \Exception('参数错误，没有limit属性');
        }

        $this->_limitRows = $config['query']['limit'];
        $this->_page = $config['page'];

        $this->_collection = $config['collection'];

        if (isset($config['skip'])) {
            $this->_skip = $config['skip'];
        }
    }

    /**
     * Returns a slice of the resultset to show in the pagination
     *
     * @throws Exception
     * @return \stdClass
     */
    public function getPaginate()
    {
        $query = $this->_query;
        if (isset($query['limit'])) {
            unset($query['limit']);
        }
        if (isset($query['skip'])) {
            unset($query['skip']);
        }
        if (isset($query['sort'])) {
            unset($query['sort']);
        }
        $limit = intval($this->_limitRows);
        $pageNumber = intval($this->_page);
        $collection = $this->_collection;
        $data = $this->_data;
        $count = $collection::count($query);
        $roundedTotal = $count > 0 ? ($count / intval($limit)) : 0;
        $totalPages = (int)$roundedTotal;

        /**
         * Increase total_pages if wasn't integer
         */
        if ($totalPages != $roundedTotal) {
            $totalPages++;
        }

        $pagination = paginator($totalPages, $pageNumber, $this->_skip);

        $page = new \stdClass();
        $page->pagination = $pagination;
        $page->items = $data;
        $page->next = isset($pagination[$pageNumber + 1]) ? $pageNumber + 1 : null;
        $page->first = 1;
        $page->before = isset($pagination[$pageNumber - 1]) ? $pageNumber - 1 : null;
        $page->current = $pageNumber;
        $page->last = $totalPages;
        $page->total_pages = $totalPages;
        $page->total_items = $count;

        return $page;
    }
}